package org.example.common;

import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import org.example.constans.GlobalErrorCodeConstants;
import org.example.exception.ServiceException;

import java.io.Serializable;

/**
 * @author WN
 * @date：2024/03/25 10:23
 */
@Data
public class CommonResult<T> implements Serializable {
    /**
     * 状态码
     */
    private Integer code;

    /**
     * 数据
     */
    private T data;

    /**
     * 错误信息
     */
    private String msg;

    public static <T> CommonResult<T> error(Integer code, String msg) {
        CommonResult<T> result = new CommonResult<>();
        result.setCode(code);
        result.setMsg(msg);
        return result;
    }

    public static <T> CommonResult<T> error(CommonResult<T> result) {
        return error(result.getCode(), result.getMsg());
    }

    public static <T> CommonResult<T> success(T data) {
        CommonResult<T> result = new CommonResult<>();
        result.setCode(GlobalErrorCodeConstants.SUCCESS.getCode());
        result.setData(data);
        return result;
    }

    @JsonIgnore
    public Boolean isSuccess() {
        return this.code.equals(GlobalErrorCodeConstants.SUCCESS.getCode());
    }

    @JsonIgnore
    public void getCheckErrorData() throws ServiceException{
        checkError();
    }

    public void checkError(){
        if(isSuccess()){
            return;
        }
        throw new ServiceException(this.msg);
    }
}
